package top.wuyang.trywork.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.wuyang.trywork.base.PageBean;
import top.wuyang.trywork.base.R;
import top.wuyang.trywork.dao.TbGameMapper;
import top.wuyang.trywork.dao.TbGamePublisherMapper;
import top.wuyang.trywork.entity.TbGame;
import top.wuyang.trywork.entity.TbGamePublisher;
import top.wuyang.trywork.service.TbGameService;
import top.wuyang.trywork.vo.PageVO;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbGameServiceImpl implements TbGameService {

    private final TbGameMapper tbGameMapper;
    private final TbGamePublisherMapper tbGamePublisherMapper;

    @Override
    public R<String> insert(TbGame tbGame){
        TbGamePublisher publisher = tbGamePublisherMapper.selectById(tbGame.getGpid());
        if (publisher == null) {
            return R.fail("游戏发行商不存在", null);
        }
        int i = tbGameMapper.insert(tbGame);
        return i == 1 ? R.ok("新增成功", null) : R.fail("新增失败", null);
    }

    @Override
    public R<PageVO<TbGame>> query(TbGame tbGame, PageBean pageBean){
        IPage<TbGame> page = new Page<>(pageBean.getPageNumber(), pageBean.getPageSize());
        QueryWrapper<TbGame> wrapper = new QueryWrapper<>();
        wrapper.eq(tbGame.getGpid() != null,"gpid",tbGame.getGpid());
        wrapper.like(StringUtils.hasText(tbGame.getGname()),"gname",tbGame.getGname());
        page= tbGameMapper.selectPage(page, wrapper);
        return R.ok(page);
    }

    @Override
    public R<TbGame> queryById(Integer id) {
        TbGame tbGame = tbGameMapper.selectById(id);
        return tbGame == null ? R.fail("主键不存在", null) : R.ok("查询成功", tbGame);
    }

    @Override
    public R<String> update(TbGame tbGame){
        TbGamePublisher publisher = tbGamePublisherMapper.selectById(tbGame.getGpid());
        if (publisher == null) {
            return R.fail("游戏发行商不存在", null);
        }
        int i = tbGameMapper.updateById(tbGame);
        return i == 1 ? R.ok("修改成功", null) : R.fail("修改失败", null);
    }

    @Override
    public R<String> delete(Integer id){
        int i = tbGameMapper.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("主键不存在", null);
    }





}
